import { Component, Node, Button, _decorator, NodeEventType, Label, Slider, EditBox, ProgressBar } from "cc";
import { JeesContainer } from "./JeesContainer";

/**
 * JeesPage
 * 页面基类，页面脚本继承该组件可实现以下功能
 * 
 * 1. 按钮点击(Button)监听
 * 2. 节点点击(Node)监听
 * 3. 子组件获取
 */
export class JeesPage extends Component {

    // 按路径名称存放节点组件
    protected view: Record<string, Node> = {};
    // 按照ui类型存放节点组件
    protected ui: JeesContainer = new JeesContainer();

    onLoad() {
        this.view = {};

        this.loadViews(this.node, '');

        // this.loadUI(this.node, ['All']);
    }

    loadUI(_root: Node, _type_enabled?: any[]) {
        this.ui.load(_root, _type_enabled);
    }

    loadViews(_root: Node, _path: string) {
        for (let i = 0; i < _root.children.length; i++) {
            this.view[_path + _root.children[i].name] = _root.children[i];
            this.loadViews(_root.children[i], _path + _root.children[i].name + '/');
        }
    }

    /**
     * 对按钮进行点击事件监听 
     * @param _view_name 按钮名称
     * @param _caller 组件调用者
     * @param func 点击事件回调
     */
    addButtonListen(_view_name: string, _caller: Component, func: Function) {
        let viewNode = this.view[_view_name];
        if (!viewNode) return;
        let button = viewNode.getComponent(Button);
        if (!button) return;
        viewNode.on('click', func, _caller);
    }

    removeButtonListen(_view_name: string, _caller: Component, func: Function) {
        let viewNode: Node = this.view[_view_name];
        if (!viewNode) return;
        let button: Button | null = viewNode.getComponent(Button);
        if (!button) return;
        viewNode.off('click', func, _caller);
    }

    addNodeListen(_name: string, _type: string | NodeEventType, func: Function) {
        let node = this.getNode(_name);
        if (!node) return;
        node.on('click', func);
    }

    removeNodeListen(_name: string, _type: string | NodeEventType, func: Function) {
        let node = this.getNode(_name);
        if (!node) return;
        node.off('click', func);
    }

    getNode(key: string): Node | null {
        return this.ui.getNode(key) || null;
    }

    getButton(key: string): Button | null {
        return this.ui.getButton(key) || null;
    }

    getLabel(key: string): Label | null {
        return this.ui.getLabel(key) || null;
    }

    getSlider(key: string): Slider | null {
        return this.ui.getSlider(key) || null;
    }

    getEditBox(key: string): EditBox | null {
        return this.ui.getEditBox(key) || null;
    }

    getProgressBar(key: string): ProgressBar | null {
        return this.ui.getProgressBar(key) || null;
    }

}